﻿using System.Windows;
using System.Windows.Interactivity;
using System.Windows.Media;

namespace FirstFloor.Documents.Presentation.Behaviors
{
    /// <summary>
    /// A simple behavior automatically adjusting the clip rectangle to the actual bounds of the associated object.
    /// </summary>
    public class ClipToBoundsBehavior
        : Behavior<FrameworkElement>
    {
        /// <summary>
        /// Called after the behavior is attached to an AssociatedObject.
        /// </summary>
        /// <remarks>Override this to hook up functionality to the AssociatedObject.</remarks>
        protected override void OnAttached()
        {
            base.OnAttached();

            this.AssociatedObject.SizeChanged += OnSizeChanged;
        }

        /// <summary>
        /// Called when the behavior is being detached from its AssociatedObject, but before it has actually occurred.
        /// </summary>
        /// <remarks>Override this to unhook functionality from the AssociatedObject.</remarks>
        protected override void OnDetaching()
        {
            base.OnDetaching();

            this.AssociatedObject.SizeChanged -= OnSizeChanged;
        }

        private void OnSizeChanged(object sender, SizeChangedEventArgs e)
        {
            this.AssociatedObject.Clip = new RectangleGeometry() {
                Rect = new Rect(0,0, this.AssociatedObject.ActualWidth, this.AssociatedObject.ActualHeight)
            };
        }
    }
}
